package org.bobdawg.app.MALforAndroid;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

public class main extends Activity {

	private final static String sLOG_NAME = "MAL Main";
	private final static String sPref_SavedTab = "savedTab";
	static final int ANIME_TAB = 0;
	static final int MANGA_TAB = 1;

	//private TextView title;
	private TabHost mTabs; 
	private ListView mLvAnime;
	private ListView mLvManga;	
	private Spinner mSpinnerAnime;
	private Spinner mSpinnerManga;
	private SQLiteDatabase mDb;
	private SimpleCursorAdapter mAdapterAnime;
	private SimpleCursorAdapter mAdapterManga;
	private String mSort;
	private int mLastChoice;
	private Reciever mRec;
	private IntentFilter mIntentFilter;

	private IntegerPicker mIpWatched;
	//private IntegerPicker ipScore;
	private RatingPicker mRpScore;
	private IntegerPicker mIpVolumes;
	private MALRecord mLongClickRecord;
	
	GoogleAnalyticsTracker tracker;
	
	private SharedPreferences mPrefs;


	//private boolean animeMode;

	// private MALAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// setup analytics
		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.startNewSession("UA-25348834-2", 300, this);
		
		// track page view
		tracker.trackPageView("/main");
		
		mTabs = (TabHost) this.findViewById(R.id.my_tabhost);
		mTabs.setup();
		
		TabSpec tspec1 = mTabs.newTabSpec("First Tab");
		tspec1.setIndicator("Anime",getResources().getDrawable(R.drawable.ic_tab_tv));
		tspec1.setContent(R.id.contentAnime);
		mTabs.addTab(tspec1);
		
		TabSpec tspec2 = mTabs.newTabSpec("second Tab");
		tspec2.setIndicator("Manga",getResources().getDrawable(R.drawable.ic_tab_book));
		tspec2.setContent(R.id.contentManga);
		mTabs.addTab(tspec2);
		
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		
		if(mPrefs.getBoolean("saveTab", Boolean.parseBoolean(getString(R.string.prefSaveTabDefault))) == true) {
			mTabs.setCurrentTab(mPrefs.getInt(sPref_SavedTab, ANIME_TAB));
		} else {
			try {
				mTabs.setCurrentTab(mPrefs.getInt("mode", ANIME_TAB));
			} catch (ClassCastException e) {
				tracker.trackEvent(
						sLOG_NAME, 
						"ERROR: " + e, 
						"ERROR: setCurrentTab: pref 'mode' value not an integer (" + e + ") defaulting to ANIME_TAB", 
						0);
				Log.e(sLOG_NAME, "setCurrentTab, pref 'mode' value not an integer", e);
				mTabs.setCurrentTab(ANIME_TAB);	
			}
		}

		//title = (TextView) findViewById(R.id.mainTitle);
		mLvAnime = (ListView) findViewById(R.id.lvAnime);
		mLvManga = (ListView) findViewById(R.id.lvManga);
		
		registerForContextMenu(mLvAnime);
		registerForContextMenu(mLvManga);
		
		mIpWatched = new IntegerPicker(this);
		mIpWatched.setOnDismissListener(new WatchDismissed());
		mIpVolumes = new IntegerPicker(this);
		mIpVolumes.setTitle("Volumes Read");
		mIpVolumes.setOnDismissListener(new VolumesDismissed());

		//ipScore = new IntegerPicker(this);
		//ipScore.setTitle("Set Score");
		//ipScore.setLimits(0, 10);
		//ipScore.setOnDismissListener(new ScoreDismissed());
		mRpScore = new RatingPicker(this);
		mRpScore.setTitle("Set Score");
		mRpScore.setOnDismissListener(new ScoreDismissed());
		
		mSpinnerAnime = (Spinner) findViewById(R.id.spinnerAnime);
		mSpinnerAnime.setOnItemSelectedListener(new FilterSelected());
		mSpinnerManga = (Spinner) findViewById(R.id.spinnerManga);
		mSpinnerManga.setOnItemSelectedListener(new FilterSelected());

		ArrayAdapter<CharSequence> spinnnerAdapterAnime;
		ArrayAdapter<CharSequence> spinnnerAdapterManga;
		
		spinnnerAdapterAnime = ArrayAdapter.createFromResource(this, R.array.filterArray, android.R.layout.simple_spinner_item);
		spinnnerAdapterManga = ArrayAdapter.createFromResource(this, R.array.filterArrayManga, android.R.layout.simple_spinner_item);
		
		spinnnerAdapterAnime.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnnerAdapterManga.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		mSpinnerAnime.setAdapter(spinnnerAdapterAnime);
		mSpinnerManga.setAdapter(spinnnerAdapterManga);

		if (savedInstanceState != null) {
			//animeMode = savedInstanceState.getBoolean("mode", true);
			//initList();
			mSort = savedInstanceState.getString("sort");
			mSpinnerAnime.setSelection(savedInstanceState.getInt("filter"));
			mLastChoice = Integer.valueOf(savedInstanceState.getInt("filter"));
		} else {
			//animeMode = perfs.getString("mode", getString(R.string.prefModeDefault)).equals(getString(R.string.prefModeDefault));
			//initList();
			mSort = mPrefs.getString("sort", getString(R.string.titleSort));
			Log.i(sLOG_NAME,mPrefs.getString("filter", "0"));
			mSpinnerManga.setSelection(Integer.valueOf(mPrefs.getString("filter", "0")));
			mLastChoice = Integer.valueOf(mPrefs.getString("filter", "0"));
		}


		//adapterAnime = new MALCursorAdapter(this,R.layout.mal_item, null, new String[] { "title", "watchedEpisodes", "episodes", "score", "id" }, new int[] {
		//		R.id.title, R.id.complete, R.id.total, R.id.score, R.id.id });
		Log.d("adapterAnime", "Before");
		//mAdapterAnime = new SimpleCursorAdapter(this, R.layout.mal_item, null, new String[] { "title", "watchedEpisodes", "episodes", "score", "score", "id", "id" }, new int[] {
		//		R.id.title, R.id.complete, R.id.total, R.id.score, R.id.scoreRatingBar, R.id.image, R.id.id });
		mAdapterAnime = new SimpleCursorAdapter(this, R.layout.mal_item, null, new String[] { "title", "watchedEpisodes", "episodes", "score" }, new int[] {
				R.id.title, R.id.complete, R.id.total, R.id.score });
		Log.d("adapterAnime", "During");
		//mAdapterAnime.setViewBinder(ANIME_ITEM_VIEW_BINDER);
		mLvAnime.setAdapter(mAdapterAnime);
		Log.d("adapterAnime", "After");
		
		Log.d("adapterManga", "Before");
		mAdapterManga = new SimpleCursorAdapter(this, R.layout.mal_item_manga, null, new String[] { "title", "watchedEpisodes", "episodes", "score", "volumesRead", "volumes", "score", "id", "id" }, new int[] {
				R.id.title, R.id.complete, R.id.total, R.id.score, R.id.complete2, R.id.total2, R.id.scoreRatingBar, R.id.image, R.id.id });
		//adapterManga = new SimpleCursorAdapter(this, R.layout.mal_item_manga, null, new String[] { "title", "watchedEpisodes", "episodes", "score", "volumesRead", "volumes" }, new int[] {
		//		R.id.title, R.id.complete, R.id.total, R.id.score, R.id.complete2, R.id.total2 });
		Log.d("adapterManga", "During");
		mAdapterManga.setViewBinder(MANGA_ITEM_VIEW_BINDER);
		mLvManga.setAdapter(mAdapterManga);
		Log.d("adapterManga", "After");

		MALSqlHelper openHelper = new MALSqlHelper(this.getBaseContext());
		mDb = openHelper.getReadableDatabase();

		registerForContextMenu(mLvAnime);
		registerForContextMenu(mLvManga);

		FilterSelected fs = new FilterSelected();
		mSpinnerAnime.setOnItemSelectedListener(fs);
		mSpinnerManga.setOnItemSelectedListener(fs);
		mLvAnime.setOnItemClickListener(new AnimeSelected(getBaseContext()));
		mLvManga.setOnItemClickListener(new MangaSelected(getBaseContext()));

		mIntentFilter = new IntentFilter(MALManager.RELOAD);

		mRec = new Reciever();

		registerReceiver(mRec, mIntentFilter);
		
		setFilter(mLastChoice);

		if (mPrefs.getString("userName", "").equals("") || mPrefs.getString("passwd", "").equals("") || mPrefs.getString("api", "").equals("")) {
			Intent i = new Intent(this, Preferences.class);
			startActivity(i);
			if (mPrefs.getString("userName", "").equals("") || mPrefs.getString("", "").equals("")) {
				Toast.makeText(this, R.string.accountSetup, Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, R.string.apiSetup, Toast.LENGTH_LONG).show();
			}
		}

	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putInt(sPref_SavedTab, mTabs.getCurrentTab());
		
		editor.commit();
	}
	
	/**
	 * Bind and manipulate the <code>scoreRatingBar</code> and preview <code>imageView</code> to their respective data sources.
	 */
	final ViewBinder ANIME_ITEM_VIEW_BINDER = new ViewBinder() {
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			Log.d("MAL_Item_Anime", "ViewBinder (Start)");
			if (view.getId() != R.id.scoreRatingBar && view.getId() != R.id.image) {
				Log.d("MAL_Item_Anime", "ViewBinder (End)");
		        return false;
			}
			else if (view.getId() == R.id.scoreRatingBar) {
				
				float score = (float) cursor.getInt(columnIndex) / (float) 2;
				Log.d("MAL_Item_Anime", "ViewBinder, Score RatingBar [Start] (Score: "+ String.valueOf(score) +")");
				//RatingBar rbScore = (RatingBar) view;
				((RatingBar) view).setRating(score);
				Log.d("MAL_Item_Anime", "ViewBinder, Score RatingBar [End] (Score: "+ String.valueOf(score) +")");
				return true;
			}
			else if (view.getId() == R.id.image) {
				long id = (long) cursor.getLong(columnIndex);
				Log.d("MAL_Item_Anime", "ViewBinder, Image [Start] (Anime ID: "+ String.valueOf(id) +")");
				
				File root = Environment.getExternalStorageDirectory();
				File file;
				
				//Intent i = new Intent(this, MALManager.class);
				//i.setAction(MALManager.IMAGE);
				//Bundle b = new Bundle();
				//b.putSerializable("media", ar);
				//i.putExtras(b);
				
				file = new File(root, getString(R.string.imagePathAnime) //"Android/data/org.bobdawg.app.MALUpdater/anime/" 
						+ String.valueOf(id));
				if (file.exists()) {

					try {
						FileInputStream fis = new FileInputStream(file);
						Bitmap bmImg = BitmapFactory.decodeStream(fis);
						if (bmImg != null) {
							((ImageView) view).setImageBitmap(bmImg);
						} else {
							((ImageView) view).setImageResource(R.drawable.ic_tv_preview_placeholder);
							//startService(i);
						}
					} catch (FileNotFoundException e) {
						Log.e("MAL_Item_Anime", "ViewBinder, Error, image file not found (Anime ID: "+ String.valueOf(id) +")", e);
						((ImageView) view).setImageResource(R.drawable.ic_tv_preview_placeholder);
					}

				} else {
					Log.d("MAL_Item_Anime", "ViewBinder, image file does not exist (Anime ID: "+ String.valueOf(id) +")");
					((ImageView) view).setImageResource(R.drawable.ic_tv_preview_placeholder);
					//startService(i);
				}
				Log.d("MAL_Item_Anime", "ViewBinder, Image [End] (Anime ID: "+ String.valueOf(id) +")");
				
				return true;
			}
			else {
				Log.d("MAL_Item_Anime", "ViewBinder (End)");
				return false;
			}
		}
	};
	
	/**
	 * Bind and manipulate the <code>scoreRatingBar</code> and preview <code>imageView</code> to their respective data sources.
	 */
	final ViewBinder MANGA_ITEM_VIEW_BINDER = new ViewBinder() {
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			Log.d("MAL_Item_Manga", "View Binder (Start)");
			if (view.getId() != R.id.scoreRatingBar && view.getId() != R.id.image) {
		        return false;
			}
			else if (view.getId() == R.id.scoreRatingBar) {
				float score = (float) cursor.getInt(columnIndex) / (float) 2;
				//RatingBar rbScore = (RatingBar) view;
				((RatingBar) view).setRating(score);
				return true;
			}
			else if (view.getId() == R.id.image) {
				long id = (long) cursor.getLong(columnIndex);
				Log.d("MAL_Item_Manga", "ViewBinder, Image [Start] (Manga ID: "+ String.valueOf(id) +")");
				
				File root = Environment.getExternalStorageDirectory();
				File file;
				
				//Intent i = new Intent(this, MALManager.class);
				//i.setAction(MALManager.IMAGE);
				//Bundle b = new Bundle();
				//b.putSerializable("media", ar);
				//i.putExtras(b);
				
				file = new File(root, getString(R.string.imagePathManga) //"Android/data/org.bobdawg.app.MALUpdater/manga/" 
						+ String.valueOf(id));
				if (file.exists()) {

					try {
						FileInputStream fis = new FileInputStream(file);
						Bitmap bmImg = BitmapFactory.decodeStream(fis);
						if (bmImg != null) {
							((ImageView) view).setImageBitmap(bmImg);
						} else {
							((ImageView) view).setImageResource(R.drawable.ic_book_preview_placeholder);
							//startService(i);
						}
					} catch (FileNotFoundException e) {
						Log.e("MAL_Item_Manga", "ViewBinder, Error, image file not found (Manga ID: "+ String.valueOf(id) +")", e);
						((ImageView) view).setImageResource(R.drawable.ic_book_preview_placeholder);
					}

				} else {
					Log.d("MAL_Item_Manga", "ViewBinder, image file does not exist (Manga ID: "+ String.valueOf(id) +")");
					((ImageView) view).setImageResource(R.drawable.ic_book_preview_placeholder);
					//startService(i);
				}
				Log.d("MAL_Item_Manga", "ViewBinder, Image [End] (Manga ID: "+ String.valueOf(id) +")");
				
				return true;
			}
			else {
				return false;
			}
		}
	};

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();

		if (mTabs.getCurrentTab() == 0) {
			inflater.inflate(R.menu.item_menu, menu);
			mLongClickRecord = MALManager.getAnime(((AdapterContextMenuInfo) menuInfo).id, this.getBaseContext());
		} else {
			inflater.inflate(R.menu.item_menu_manga, menu);
			mLongClickRecord = MALManager.getManga(((AdapterContextMenuInfo) menuInfo).id, this.getBaseContext());
		}

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		boolean postIntent = false;
		int totalEp;
		int completed;

		switch (item.getItemId()) {
			case R.id.itemStatusCompleted:
				mLongClickRecord.watchedStatus = "completed";
				postIntent = true;
				break;
			case R.id.itemStatusReading:
				mLongClickRecord.watchedStatus = "reading";
				postIntent = true;
				break;
			case R.id.itemStatusDropped:
				mLongClickRecord.watchedStatus = "dropped";
				postIntent = true;
				break;
			case R.id.itemStatusOnHold:
				mLongClickRecord.watchedStatus = "on-hold";
				postIntent = true;
				break;
			case R.id.itemStatusPlantoWatch:
				mLongClickRecord.watchedStatus = "plan to watch";
				postIntent = true;
				break;
			case R.id.itemStatusPlantoRead:
				mLongClickRecord.watchedStatus = "plan to read";
				postIntent = true;
				break;
			case R.id.itemStatusWatching:
				mLongClickRecord.watchedStatus = "watching";
				postIntent = true;
				break;
			case R.id.setWatched:
				if (mLongClickRecord instanceof AnimeRecord) {
					mIpWatched.setTitle("Episodes Watched");
					totalEp = ((AnimeRecord) mLongClickRecord).episodes;
					completed = ((AnimeRecord) mLongClickRecord).watchedEpisodes;
				} else {
					mIpWatched.setTitle("Chapters Read");
					totalEp = ((MangaRecord) mLongClickRecord).chapters;
					completed = ((MangaRecord) mLongClickRecord).chaptersRead;
				}

				if (totalEp == 0) {
					totalEp = Integer.MAX_VALUE;
				}
				mIpWatched.setLimits(0, totalEp);
				mIpWatched.setCurrent(completed);
				mIpWatched.show();

				break;
			case R.id.setVolumeRead:

				totalEp = ((MangaRecord) mLongClickRecord).volumes;
				completed = ((MangaRecord) mLongClickRecord).volumesRead;

				if (totalEp == 0) {
					totalEp = Integer.MAX_VALUE;
				}
				mIpVolumes.setLimits(0, totalEp);
				mIpVolumes.setCurrent(completed);
				mIpVolumes.show();

				break;
			case R.id.setScore:

				//ipScore.setLimits(0, 10);
				//ipScore.setCurrent(longClickRecord.score);
				//ipScore.show();
				mRpScore.setCurrentRating((float) mLongClickRecord.score / (float) 2);
				mRpScore.show();

				break;
			case R.id.menuItemDelete:
				Intent i = new Intent(this, MALManager.class);
				i.setAction(MALManager.REMOVE);
				Bundle b = new Bundle();
				b.putSerializable("media", mLongClickRecord);
				i.putExtras(b);
				startService(i);
				break;
		}

		if (postIntent) {
			Intent i = new Intent(this, MALManager.class);
			i.setAction(MALManager.CHANGE);
			Bundle b = new Bundle();
			b.putSerializable("media", mLongClickRecord);
			i.putExtras(b);
			startService(i);
		}

		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public void onPause() {
		unregisterReceiver(mRec);
		// adapter.getCursor().close();
		super.onPause();
	}

	@Override
	public void onResume() {
		setFilter(mLastChoice);
		registerReceiver(mRec, mIntentFilter);
		super.onPause();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Intent i;
		switch (id) {
			case R.id.sortTitle:
				mSort = getString(R.string.titleSort);
				setFilter(mLastChoice);
				break;
			case R.id.sortScore:
				mSort = getString(R.string.scoreSort);
				setFilter(mLastChoice);
				break;
			case R.id.sortComplete:
				mSort = getString(R.string.completeSort);
				setFilter(mLastChoice);
				break;
			case R.id.menuSync:
				i = new Intent(this, MALManager.class);
				i.setAction(MALManager.SYNC);
				startService(i);
				break;
			case R.id.menuSettings:
				i = new Intent(this, Preferences.class);
				startActivity(i);
				break;
			case R.id.menuAdd:
				i = new Intent(this, Search.class);
				Bundle b = new Bundle();
				b.putBoolean("mode", mTabs.getCurrentTab() == 0);
				i.putExtras(b);				
				startActivity(i);
				break;
		}
		return true;
	}

	public void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putString("sort", mSort);
		savedInstanceState.putInt("filter", mLastChoice);
		//savedInstanceState.putBoolean("mode", animeMode);

		super.onSaveInstanceState(savedInstanceState);
	}

	/**
	 * 
	 * @param choice
	 */
	private void setFilter(int choice) {
		mLastChoice = choice;
		//String query;
		//if (animeMode) {
		String queryAnime = getString(R.string.cursorSelect) + getResources().getStringArray(R.array.filterWhere)[choice] + " and dirty <> 3 " + mSort;
		//} else {
		String queryManga = getString(R.string.cursorSelectManga) + getResources().getStringArray(R.array.filterWhereManga)[choice] + " and dirty <> 3 " + mSort;
		//}
		
		if ( mSpinnerManga.getSelectedItemId() != choice ){
			mSpinnerManga.setSelection(choice);
		}
		
		if ( mSpinnerAnime.getSelectedItemId() != choice ){
			mSpinnerAnime.setSelection(choice);
		}

		try {
			// adapter.getCursor().close();
			Cursor cAnime = mDb.rawQuery(queryAnime, null);
			mAdapterAnime.changeCursor(cAnime);
			Cursor cManga = mDb.rawQuery(queryManga, null);
			mAdapterManga.changeCursor(cManga);
		} catch (Exception e) {
			Log.e("main", "Query failure", e);			
		}

	}

	/**
	 * 
	 * @author Robert LaFont Jr
	 *
	 */
	private class FilterSelected implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
			setFilter(position);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}

	private class AnimeSelected implements OnItemClickListener {

		private Context context;

		public AnimeSelected(Context context) {
			this.context = context;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
			// Toast.makeText(context, "item: "+ String.valueOf(id),
			// Toast.LENGTH_LONG).show();
			Intent i = new Intent(context, AnimeDetail.class);
			Bundle b = new Bundle();
			//if (animeMode) {
				b.putSerializable("media", MALManager.getAnime(id, getBaseContext()));
				tracker.trackEvent("Anime List Item", "Clicked", "Anime ID | " + String.valueOf(id), 0);
			/*} else {
				b.putSerializable("media", MALManager.getManga(id, getBaseContext()));
			}*/
			i.putExtras(b);
			startActivity(i);
		}

	}
	
	private class MangaSelected implements OnItemClickListener {

		private Context context;

		public MangaSelected(Context context) {
			this.context = context;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
			// Toast.makeText(context, "item: "+ String.valueOf(id),
			// Toast.LENGTH_LONG).show();
			Intent i = new Intent(context, AnimeDetail.class);
			Bundle b = new Bundle();
			//if (animeMode) {
			//	b.putSerializable("media", MALManager.getAnime(id, getBaseContext()));
			//} else {
				b.putSerializable("media", MALManager.getManga(id, getBaseContext()));
				tracker.trackEvent("Manga List Item", "Clicked", "Manga ID | " + String.valueOf(id), 0);
			//}
			i.putExtras(b);
			startActivity(i);
		}

	}

	private class Reciever extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			Log.i(sLOG_NAME, arg1.getAction());
			setFilter(mLastChoice);
		}

	}

	private class WatchDismissed implements OnDismissListener {
		@Override
		public void onDismiss(DialogInterface dialog) {
			if (!mIpWatched.wasCanceled()) {

				Intent i = new Intent(getBaseContext(), MALManager.class);
				i.setAction(MALManager.CHANGE);
				Bundle b = new Bundle();
				if (mLongClickRecord instanceof AnimeRecord) {
					((AnimeRecord) mLongClickRecord).watchedEpisodes = mIpWatched.getCurrent();
				} else {
					((MangaRecord) mLongClickRecord).chaptersRead = mIpWatched.getCurrent();
				}
				b.putSerializable("media", mLongClickRecord);

				i.putExtras(b);
				startService(i);

			}
		}
	}

	private class VolumesDismissed implements OnDismissListener {
		@Override
		public void onDismiss(DialogInterface dialog) {
			if (!mIpVolumes.wasCanceled()) {

				Intent i = new Intent(getBaseContext(), MALManager.class);
				i.setAction(MALManager.CHANGE);
				Bundle b = new Bundle();

				((MangaRecord) mLongClickRecord).volumesRead = mIpVolumes.getCurrent();
				b.putSerializable("media", mLongClickRecord);

				i.putExtras(b);
				startService(i);

			}
		}
	}

	private class ScoreDismissed implements OnDismissListener {
		@Override
		public void onDismiss(DialogInterface dialog) {
			//if (!ipScore.wasCanceled()) {
			if (!mRpScore.wasCanceled()) {

				Intent i = new Intent(getBaseContext(), MALManager.class);
				i.setAction(MALManager.CHANGE);
				Bundle b = new Bundle();
				//longClickRecord.score = ipScore.getCurrent();
				mLongClickRecord.score = (int) (mRpScore.getCurrentRating() * (float) 2);
				b.putSerializable("media", mLongClickRecord);

				i.putExtras(b);
				startService(i);

			}
		}
	}	
}
